import React, { Component } from 'react';
import Taro,{getCurrentInstance} from '@tarojs/taro';
import { View, Text, Button, ScrollView, Image } from '@tarojs/components';
import { Search, Toast } from '@antmjs/vantui';
import { findNameByFieldNameAndDictItemValue } from '@/services/api/common';
import { changeDecimalToPercentage, parseDateFromStr } from '@/utils/fomatter';
import { searchFundPoolFormName, submitFundFeedback } from '@/services/api/fund';

import './index.scss'
import FundFeedbackPopup from './pop';
import PdsEmpty from '@/components/common/pds_empty';
import { saveHistory } from '../history';

class FundSearchResult extends Component {

    config = {
        navigationBarTitleText: ''
    }

    state = {
        basicsList: [],
        refresherTriggered: false,
        searchName: '',
        isExist: true,
        feedbackPopUp: false,
        searchFoucs:true,
    }

      // 建议在页面初始化时把 getCurrentInstance() 的结果保存下来供后面使用，
    // 而不是频繁地调用此 API
    $instance = getCurrentInstance()

    componentWillMount() {
        var params = this.$instance.router?.params;
        if(params && params['searchName'] !== null){
            this.setState({ searchName: params['searchName'] },()=>{
                this.requestListData(false)
            })
        }
    }
    componentDidMount() { }
    componentWillReceiveProps(nextProps, nextContext) { }
    componentWillUnmount() { }
    componentDidShow() { }
    componentDidHide() { }
    componentDidCatchError() { }
    componentDidNotFound() { }


    requestListData(isAdd) {
        const { searchName } = this.state
        searchFundPoolFormName(searchName).then((resp) => {
            if (resp.code === 200) {
                saveHistory(searchName)
                this.setState({ basicsList: resp.data['funds'], isExist: resp.data['isExist'] })
            }
            this.setState({searchFoucs:false})
        })
    }


    //自定义下拉刷新被触发
    onRefresherRefresh(e) {
        this.setState({ refresherTriggered: true })
        console.log(e, '自定义下拉刷新被触发')
        this.requestListData(false);
    }

    // 滚动到底部上拉加载
    // scrolltoLower() {
    //     this.requestListData(true);
    // }

    /**
     * 快速滑动不触发onScrollToLower 的bug
     * @param param0 
     */
    // onScroll = ({ detail: { scrollTop, scrollHeight } }) => {
    //     const { screenHeight, } = Taro.getSystemInfoSync()
    //     if (
    //         scrollTop + screenHeight + 100 >= scrollHeight
    //     ) {
    //         this.scrolltoLower(); // 手动触发 onScrollToLower
    //     }
    // };

    /**
     * 点击一道投的产品
     */
    clickYdtFund(item) {
        console.log(item)
    }

    /**
     * 点击外部的产品
     * 
     */
    clickXhFund() {

    }

    /**
     * 点击搜索框
     */
    clickSearch() {
        const { searchName } = this.state;
        if (searchName.length == 0) {
            Toast.show('请输入搜索内容')
            return
        }
        this.requestListData(false)
    }

    /**
     * 搜索文本变化
     * @param value 
     */
    changeSearchText(value) {
        this.setState({ searchName: value.detail })
    }

    /**
     * 点击反馈
     */
    clickFeedbackPopUp() {
        this.setState({ feedbackPopUp: true })
    }
    
    /**
     * 点击协会产品反馈
     * @param item 
     */
    clickFeedbackFund(item){
        var feedback_type = 1;
        var fund_code = item['fundCode'];
        var fund_name = item['fundName'];
        submitFundFeedback({ feedback_type, fund_code, fund_name }).then((resp) => {
            if(resp.code === 200){
                Toast.show('反馈成功')
            }
        });
    }

    render() {
        const { basicsList, refresherTriggered, feedbackPopUp, isExist,searchFoucs,searchName } = this.state
        const { safeArea } = Taro.getSystemInfoSync();
        const scrollTop = 0

        return (
            <View className='page'>
                <Search focus={searchFoucs} defaultValue={searchName} placeholder="搜索私募基金产品" inputAlign="left" onFocus={(e) => {
                    this.setState({searchFoucs:true})
                }} onBlur={(e) => {
                    this.setState({searchFoucs:false})
                }} renderAction={<View onClick={this.clickSearch.bind(this)}>搜索</View>} onSearch={this.clickSearch.bind(this)} onChange={(e) => this.changeSearchText(e)}></Search>
                {basicsList.length > 0 ?
                    <ScrollView
                        className='scrollview'
                        scrollY
                        scrollWithAnimation
                        refresherEnabled
                        scrollTop={scrollTop}
                        refresherTriggered={refresherTriggered}
                        lowerThreshold={100}
                        onRefresherRefresh={this.onRefresherRefresh.bind(this)} // 使用箭头函数的时候 可以这样写 `onScrollToUpper={this.onScrollToUpper}`
                    // onScrollToLower={this.scrolltoLower.bind(this)}
                    // onScroll={this.onScroll.bind(this)}
                    >   
                        {
                          basicsList.length === 0 ? <PdsEmpty placeholderText='没有搜索相关私募基金'></PdsEmpty>  :null
                        }
                        {
                            (basicsList.length > 0 && !isExist) ? <View className='fund-search-header'>
                                <Image src={require('@/assets/images/hot-news.png')} ></Image>
                                <View>没有找到匹配的产品，搜点别的试试？</View>
                                <View className='fund-search-header-bottom'>
                                    或<View className='bottom-click' onClick={this.clickFeedbackPopUp.bind(this)}> 点这里 </View>向我们反馈
                                </View>

                            </View> : null
                        }
                        {
                            basicsList.length > 0 ?
                                !isExist ? <Text className='page-top' space='nbsp' decode>
                                    {`-&nbsp;&nbsp;热搜产品&nbsp;&nbsp;-`}
                                </Text> :
                                    <Text className='page-top' space='nbsp' decode>
                                        {`-&nbsp;&nbsp;为你找到&nbsp;&nbsp;${basicsList.length}&nbsp;&nbsp;个产品&nbsp;&nbsp;-`}
                                    </Text>
                                : null
                        }

                        {
                            basicsList.map((item, index) => {

                                return item['fundDataSource'] === 1 ?
                                    <View className='fund-item ydt-fund-item' onClick={() => this.clickYdtFund(item)}>
                                        <View className='title-icon'>
                                            <Text>{item['fundName']}</Text>
                                        </View>
                                        <View className='fund-tag'>
                                            <View className='ydt-icon'>
                                                <Image src={require('@/assets/icons/public/fund_list_ydt.svg')} style={{ width: 10, height: 10, }}></Image>
                                            </View>
                                            {
                                                (item['policyType'] !== undefined && item['policyType'] !== -1 && item['policyType'] !== 0) ? <View className='fund-tag-item ydt-tag-item'>{findNameByFieldNameAndDictItemValue('policy_type', item['policyType'])}</View> : null
                                            }
                                            {
                                                (item['fundType'] !== undefined && item['fundType'] !== -1 && item['fundType'] !== 0) ? <View className='fund-tag-item ydt-tag-item '>{findNameByFieldNameAndDictItemValue('fund_type', item['fundType'])}</View> : null
                                            }
                                            {
                                                (item['riskLevel'] !== undefined && item['riskLevel'] !== -1 && item['riskLevel'] !== 0) ? <View className='fund-tag-item ydt-tag-item'>{`产品评级:${findNameByFieldNameAndDictItemValue('risk_level', item['riskLevel'])}`}</View> : null
                                            }
                                        </View>
                                        <View className='fund-context'>
                                            <View className='fund-context-item  zdf'>
                                                <View className={Number(item['performance']['yearRate']) > 0 ? '.num-positive-text' : (Number(item['performance']['yearRate']) < 0 ? 'num-negative-text' : '')}><Text>{`${Number(item['performance']['yearRate']) > 0 ? '+' : ''}`}{changeDecimalToPercentage(item['performance']['yearRate'], 2)}</Text>%</View>
                                                <View className='fund-context-item-desc'>近一年涨跌幅</View>
                                            </View>
                                            <View className='fund-context-item  fbq'>
                                                <View className=''>{item['subscribeThreshold'].length > 0 ? `${Number(item['subscribeThreshold'] / 10000).toFixed(2)}万起` : '-'}</View>
                                                <View className='fund-context-item-desc'>{item['fundClosingPeriod'].length > 0 ? item['fundClosingPeriod'] : '-'} | {findNameByFieldNameAndDictItemValue('risk_level', item['riskLevel'])}</View>
                                            </View>
                                            <View className='fund-context-item  dwjz'>
                                                <View className=''>{Number(item['performance']['unitNet']).toFixed(4)}</View>
                                                <View className='fund-context-item-desc'>{`单位净值(${(item['performance']['netDate'] !== undefined && item['performance']['netDate'] !== null && item['performance']['netDate'] !== 0) ? parseDateFromStr(item['performance']['netDate'], 'MM-DD') : '-'})`}</View>
                                            </View>
                                        </View>
                                    </View>

                                    : <View className='fund-item xh-fund-item'>
                                        <View className='title-icon'>
                                            <Text>{item['fundName']}</Text>
                                        </View>
                                        <View className='fund-tag'>
                                            {
                                                (item['fundCode'] !== undefined) ? <View className='fund-tag-item xh-tag-item'>{item['fundCode']}</View> : null
                                            }
                                            {
                                                (item['fundCategory'] !== undefined && item['fundCategory'] !== -1 && item['fundCategory'] !== 0) ? <View className='fund-tag-item xh-tag-item '>{findNameByFieldNameAndDictItemValue('fund_category', item['fundCategory'])}</View> : null
                                            }
                                        </View>
                                        <View className='bottom'>
                                            <View className='left-bottom'>
                                                <Image src={require('@/assets/icons/public/fund_list_ydt.svg')} style={{ width: 10, height: 10, }}></Image>
                                                <Text>暂未收录此基金</Text>
                                            </View>
                                            <View className={`right-bottom`} onClick={(e) => this.clickFeedbackFund(item)}>
                                                申请收录
                                            </View>
                                        </View>
                                    </View>

                            })
                        }
                    </ScrollView > : null}
                {
                    basicsList.length > 0 ? <View className='page-bottom' style={{ paddingBottom: safeArea.top }}>
                        未找到满意结果？<View className='bottom-click' onClick={this.clickFeedbackPopUp.bind(this)}>点这里 </View>  反馈
                    </View> : null
                }

                <FundFeedbackPopup showPopUP={feedbackPopUp} onClose={() => {
                    this.setState({ feedbackPopUp: false })
                }} onSubmit={() => { }}></FundFeedbackPopup>

                <Toast></Toast>
            </View>
        );
    }
}
export default FundSearchResult;